package com.cyan.app.workflow.util;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.widget.Toast;

import com.cyan.app.workflow.AppData;
import com.cyan.app.workflow.R;
import com.cyan.app.workflow.common.HttpConfig;
import com.cyan.app.workflow.customview.CustomDialog;
import com.cyan.app.workflow.customview.LoadingDialog;
import com.cyan.app.workflow.util.network.CommHttpListener;
import com.cyan.app.workflow.util.network.VolleyUtil;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by DXW on 2015/12/16.
 */
public class Upgrader {
    private static final String TAG = "Upgrader";
    private static final String UPGRADE_FILE_NAME = "upgradeFile";

    /**更新文件名*/
    public static final String UPDATE_APK_SERVER = "http://172.17.17.5:809/update/";
    //public static final String UPDATE_APK_SERVER = "http://mobile.jdd.com/android/";
    public static final String UPDATE_SAVENAME = "aaa.apk";

    private Context ctx;
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH");

    private SharedPreferences sp;

    public interface UpgraderListener {
        public void onCheckVersion(UpdateBean updateBean);

    }

    public Upgrader(Context ctx) {
        this.ctx = ctx;
        this.sp = ctx.getSharedPreferences(UPGRADE_FILE_NAME, Activity.MODE_PRIVATE);
    }

    /**
     * 静默更新
     */
    public void doUpdate() {
        String last_upgrade = sp.getString("last-upgrade", "");
        String today = sdf.format(new Date());

        /* if(last_upgrade.equals(today)) {
            return;
        }else {
            SharedPreferences.Editor edit = sp.edit();
            edit.putString("last-upgrade", today);
            edit.commit();
        }*/

        doUpdate(false);
    }

    /**
     * 手动更新
     */
    public void doUpdate(final boolean showTip) {
        Map<String, String> map = new HashMap<>();
        map.put("action", "1");
        map.put("params", "{}");
        VolleyUtil.sendStringRequestByPost(ctx, HttpConfig.HTTP_UPGRADER_SERVER_URL,TAG, map, UpdateBean.class, new CommHttpListener<UpdateBean>() {
            @Override
            public void onSuccess(UpdateBean updateBean) {
                UpdateBean.JsonData data = updateBean.getData();
                if (data != null) {
                    if (data.getVercode() > AppData.getAPPVERSIONCODE()) {
                        if (data.getBupdate() == -1) {//-1强制更新
                            isMustUpgrade = true;
                             doNewVersionUpdate2(data.getMessage().replace("\\n", "\n"), data.getApkname());
                            //doNewVersionUpdate2(data.getMessage().replace("\\n", "\n"), "app-debug.apk");
                        } else if (data.getBupdate() == 1) { //1提示更新
                            isMustUpgrade = false;
                            doNewVersionUpdate(data.getMessage().replace("\\n", "\n"), data.getApkname());
                        } else if (data.getBupdate() == 0) { //0不更新
                        }

                        /**
                         * 设置当天不提醒
                         */
                        SharedPreferences.Editor edit = sp.edit();
                        edit.putString("last-upgrade", sdf.format(new Date()));
                        edit.commit();
                    } else {
                        if (showTip) {
                            Toast.makeText(ctx, "暂无更新", Toast.LENGTH_SHORT).show();
                        }
                    }
                }
            }

            @Override
            public void onCodeError(int code, String msg) {
                if (showTip) {
                    Toast.makeText(ctx, msg, Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    /**
     * 检测更新
     * @param upgraderListener
     */
    public void checkUpdate(final UpgraderListener upgraderListener) {
        Map<String, String> map = new HashMap<>();
        map.put("action", "1");
        map.put("params", "{}");
        VolleyUtil.sendStringRequestByPost(ctx, TAG, map, UpdateBean.class, new CommHttpListener<UpdateBean>() {
            @Override
            public void onSuccess(UpdateBean updateBean) {
                if(upgraderListener != null) {
                    upgraderListener.onCheckVersion(updateBean);
                }
            }
        });
    }

    // 有检测到新版本，提示更新
    private void doNewVersionUpdate(String mes, final String name) {

        CustomDialog dialog = new CustomDialog.Builder(ctx).setTitle(R.string.upgrade_dialog_title).setMessage(mes)
                // 设置内容
                .setPositiveButton(R.string.upgrade_dialog_donot,// 设置确定按钮
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
//                                stratService();
                                dialog.cancel();
                            }
                        }).setNegativeButton(R.string.upgrade_dialog_ok, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        dialog.cancel();
                        doUpdate(name);
                    }
                }).createCustomDialog();// 创建
        // 显示对话框
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
    }

    // 有检测到新版本，强制更新
    private void doNewVersionUpdate2(final String mes, final String name) {

        CustomDialog dialog = new CustomDialog.Builder(ctx).setTitle(R.string.upgrade_dialog_title).setMessage(mes)
                // 设置内容
                .setPositiveButton(R.string.upgrade_dialog_no,// 设置确定按钮
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                                exitConfirm(mes, name);
                            }
                        }).setNegativeButton(R.string.upgrade_dialog_yes, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        dialog.dismiss();
                        doUpdate(name);
                    }
                }).setOnCancelListener(new DialogInterface.OnCancelListener() {

                    @Override
                    public void onCancel(DialogInterface dialog) {
                        dialog.cancel();
                        exitConfirm(mes, name);
                    }
                }).createCustomDialog();// 创建
        // 显示对话框
        dialog.setCancelable(false);
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
    }

    private void exitConfirm(final String mes, final String name) {
        CustomDialog dialog = new CustomDialog.Builder(ctx).setTitle(R.string.upgrade_dialog_tip)
                .setMessage(R.string.upgrade_dialog_exit_msg)
                        // 设置内容
                .setPositiveButton(R.string.upgrade_dialog_no,// 设置确定按钮
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                doNewVersionUpdate2(mes, name);
                            }
                        }).setNegativeButton(R.string.upgrade_dialog_yes, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        dialog.cancel();
                        ((Activity)ctx).finish();
                    }
                }).setMessageIcon(R.drawable.message_icon).createCustomDialog();
        dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                doNewVersionUpdate2(mes, name);
            }
        });
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
    }

    LoadingDialog pBar;
    boolean isMustUpgrade;

    // 开始更新
    private void doUpdate(String name) {
        pBar = new LoadingDialog(ctx);
        pBar.getDialog().setCancelable(true);
        pBar.getDialog().setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                isCancelDownload = true;
            }
        });
        // 下载新版本
        downFile(UPDATE_APK_SERVER + name);
    }

    boolean isCancelDownload;

    // 下载新版本
    void downFile(final String url) {
        pBar.show();
        isCancelDownload = false;
        new Thread() {
            public void run() {
                HttpClient client = new DefaultHttpClient();
                HttpGet get = new HttpGet(url);
                HttpResponse response;
                try {
                    response = client.execute(get);
                    HttpEntity entity = response.getEntity();
                    long length = entity.getContentLength();
                    int pBarmax = (int) entity.getContentLength() / 1024;
                    pBar.setMax(pBarmax);
                    InputStream is = entity.getContent();
                    FileOutputStream fileOutputStream = null;
                    if (is != null) {
                        File file = new File(Environment.getExternalStorageDirectory(),
                                UPDATE_SAVENAME);
                        fileOutputStream = new FileOutputStream(file);

                        byte[] buf = new byte[1024];
                        int ch = -1;
                        int count = 0;
                        while ((ch = is.read(buf)) != -1) {
                            fileOutputStream.write(buf, 0, ch);
                            count += ch;
                            if (pBar.getMax() > (count / 1024)) {
                                pBar.setProgress(count / 1024);
                                // pBar.setSecondaryProgress(count / 1024);
                            }
                            if (isCancelDownload)
                                break;
                        }
                    }
                    fileOutputStream.flush();
                    if (fileOutputStream != null) {
                        fileOutputStream.close();
                    }
                    if (!isCancelDownload)
                        down();
                    else {
                        // 如果是强制更新，继续弹出更新提示框
                        if (isMustUpgrade) {
                            doUpdate();
                        }
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                    pBar.cancel();
                }
            }

        }.start();
    }

    private Handler handler = new Handler();

    // 下载新版本后关闭
    void down() {
        handler.post(new Runnable() {
            public void run() {
                pBar.cancel();
                update();
            }
        });
    }

    // 下载新版本后安装
    void update() {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(
                Uri.fromFile(new File(Environment.getExternalStorageDirectory(), UPDATE_SAVENAME)),
                "application/vnd.android.package-archive");
        ctx.startActivity(intent);
        ((Activity)ctx).finish();
    }


    public class UpdateBean {

        /**
         * 下面是示例
         *
         * 请求：http://client.master.jdd.com/action/NewMobileHandler.ashx?sign=&platformVersion=4.4.4&platformCode=Android&cmdId=0&token=&appVersion=1.6.7&cmdName=app_zz&action=1&UserID=&usertype=&uuid=358239058571631&params={}
         *
         * 返回：{"Code":0,"Data":{"appname":"Soccer","apkname":"Soccer.apk","bupdate":1,"vername":"1.6.7","vercode":167,"message":"最新版本：1.6.7,\\n更新内容,\\n■ 1.新增单场比赛关注功能，实时了解赛事情况；\\n■ 2.单场比赛消息提醒可以进行单独设置，不错过每一个精彩瞬间；\\n■ 3.用户中心新增收藏栏目，方便回顾热门资讯；\\n■ 4.新增球员主页，了解球员近期战绩、个人统计数据及其职业生涯；\\n■ 5.系统优化，使用起来更流畅。"},"Msg":"","Stamp":""}
         *
         */


        private int Code;
        private JsonData Data ;
        private String Msg;
        private String Stamp;

        public int getCode() {
            return Code;
        }

        public void setCode(int code) {
            Code = code;
        }

        public JsonData getData() {
            return Data;
        }

        public void setData(JsonData data) {
            Data = data;
        }

        public String getMsg() {
            return Msg;
        }

        public void setMsg(String msg) {
            Msg = msg;
        }

        public String getStamp() {
            return Stamp;
        }

        public void setStamp(String stamp) {
            Stamp = stamp;
        }

        public class JsonData {
            private String appname;
            private String apkname;
            private int bupdate;
            private String vername;
            private int vercode;
            private String message;

            /** H5更新包名称 */
            private String zipname;

            public String getAppname() {
                return appname;
            }

            public void setAppname(String appname) {
                this.appname = appname;
            }

            public String getApkname() {
                return apkname;
            }

            public void setApkname(String apkname) {
                this.apkname = apkname;
            }

            public int getBupdate() {
                return bupdate;
            }

            public void setBupdate(int bupdate) {
                this.bupdate = bupdate;
            }

            public String getVername() {
                return vername;
            }

            public void setVername(String vername) {
                this.vername = vername;
            }

            public int getVercode() {
                return vercode;
            }

            public void setVercode(int vercode) {
                this.vercode = vercode;
            }

            public String getMessage() {
                return message;
            }

            public void setMessage(String message) {
                this.message = message;
            }

            public String getZipname() {
                return zipname;
            }

            public void setZipname(String zipname) {
                this.zipname = zipname;
            }


        }
    }
}

